# coding=utf-8
__author__ = 'liubin'

from flask import session
from flask.ext.restful import Resource, reqparse
from flask.ext.admin.contrib.sqla import ModelView
from project import api_view, admin_view, Order, OrderDetail, db


class OrderApi(Resource):
    """
    restful访问方式
    订单提交进session
    """

    def post(self, **kwargs):
        """
        restful的 post
        :param kwargs:
        :return:
        """

        # 请求参数的解析
        parser = reqparse.RequestParser()
        parser.add_argument('item_id', type=int, required=True)
        parser.add_argument('count', type=int, required=True)
        args = parser.parse_args()
        item_id = args['item_id']
        count = args['count']
        # session 操作
        # session 默认以unicode处理
        if not u'items' in session:
            session[u'items'] = {}
        if unicode(item_id) in session['items']:
            count = count + session[u'items'][unicode(item_id)]
        session[u'items'][unicode(item_id)] = count
        return {'success': True}

# 映射restful的url
api_view.add_resource(OrderApi, '/api/order')
# admin视图 订单
admin_view.add_view(ModelView(Order, db.session))
admin_view.add_view(ModelView(OrderDetail, db.session))